<?php

namespace app\controller\admin;

use app\base\BaseEncryptController;
use app\model\agency\AgencyEarningsModel;
use app\model\agency\AgencyModel;
use app\model\order\OrderModel;
use think\Request;

/**
 * AgencyEarnings 代理商收益
 * Class AgencyEarnings
 * @package app\controller
 */
class AgencyEarnings extends BaseEncryptController
{
    protected function initialize()
    {
        parent::initialize();
        $this->model = new AgencyEarningsModel();
    }

    /**
     * 分页列表
     * @param int $agency_id
     * @param int $page
     * @param int $limit
     * @return \think\response\Json
     */
    public function getPage($agency_id = 0, $page = 1, $limit = 10)
    {
        $data = $this->model->getPageData($agency_id, $page, $limit);
        return self::returnMsg(1, [
            'totalCount' => $data['total'],
            'currentPage' => $data['current'],
            'pageList' => $data['dataList']
        ]);
    }

    /**
     * 添加结算
     * @param Request $request
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addEarnings(Request $request)
    {
        $formData = $request->param();
        $time_section = isset($formData['time_section']) ? $formData['time_section'] : [];
        $end_time = time();
        if (!empty($time_section)) {
            $start_time = strtotime($time_section[0]);
            $end_time = strtotime($time_section[1]);
        }
        $agency_id = $formData['agency_id'];
        $is_ajax = isset($formData['is_ajax']) ? $formData['is_ajax'] : '';
        if (empty($start_time) || empty($end_time)) {
            $start_time = strtotime("-1 month");
        }
        if (!empty($is_ajax)) {
            $price = OrderModel::getAgencyEarnings($agency_id, $start_time, $end_time);
            $return_data['code'] = 1;
            $return_data['data'] = $price;
            return $return_data;
        }
        $price = $formData['price'];
        $order_sn = date("YmdHis") . $agency_id . mt_rand(1000, 9999);
        $pay_sn = "add" . date("YmdHis") . $agency_id . mt_rand(1000, 9999);
        $agency_model = new AgencyModel();
        $return_data = $agency_model->changeEarnings($agency_id, floatval($price), 1, 'add', $order_sn, $pay_sn);
        if ($return_data['code'] == 1) {
            OrderModel::settleAgencyOrder($agency_id, $start_time, $end_time);
        }
        return $return_data;
    }


}
